<?php

namespace App\Managers\Admin;

use App\Enums\StatingRoleEnum;
use App\Exceptions\AdminException;
use App\Managers\BaseManager;
use App\Models\AdminGroupModel;
use App\Models\AdminRoleModel;
use App\Models\AdminUserDepartmentsModel;
use App\Models\AdminUserParentsModel;
use App\Models\AdminUsers;
use App\Models\AdminUsersModel;
use App\Models\AdminUsersRolesModel;
use App\Models\AttendanceShiftModel;
use App\Models\AttendanceShiftTimeModel;
use App\Util\LoginUtil;
use Illuminate\Support\Facades\Hash;

class AdminUsersManager extends BaseManager
{
    public function __construct(AdminUsersModel $model)
    {
        parent::__construct();
        $this->model = $model;
    }


    public function _format($data)
    {

        $group_id = $data->pluck('group_id');
        $group = \App\Models\AdminGroupModel::query()->whereIn('id', $group_id)->select(['id', 'text'])->get()
            ->pluck('text', 'id');

        foreach ($data as $item) {
            data_set($item, 'password', '');
            data_set($item, 'salt', '');
            data_set($item, 'role_list', '');
            data_set($item, 'group_text', data_get($group, data_get($item, 'group_id'), ''));
            $role_info = data_get($item, 'role_info', []);

            data_set($item, 'role_list', collect($role_info)->pluck('role_id')->toArray());

        }

        return $data;
    }

    /**
     * 查询前过滤
     */
    public function _before_lists()
    {
        $is_project_manage_admin = $this->getData('is_project_manage_admin');
        //判断是否是项目负责人
        if (empty($is_project_manage_admin)){
            $this->setData('id',null);
        }
        $model = $this->model->getQueryByModel();
        $model->with(['getGreatedByUserInfo' => function ($build) {
            $build->select(['id', 'account']);
        }]);

        $model->with(['role_info' => function ($build) {
            $build->select(['admin_user_id', 'role_id']);
        }]);
    }

    public function _after_lists()
    {

    }

    public function _before_save()
    {
        if (isset($this->data['password']) && !empty($this->data['password']) && !empty($this->data['password_confirm'])) {
            if ($this->data['password'] !== $this->data['password_confirm']) {
                throw new AdminException('密码不一致');
            }
            unset($this->data['password_confirm']);
            //密码加密
            if (!empty($this->data['password'])) {
                $this->data['salt'] = Hash::make($this->data['password']);
                $salt = $this->data['salt'] . config("app.salt");
                $this->data['password'] = md5(sha1($this->data['password'] . $salt));
            }
        } else {
            unset($this->data['password']);
        }

        if (isset($this->data['pay_password']) && !empty($this->data['pay_password']) && !empty($this->data['pay_password_confirm'])) {
            if ($this->data['pay_password'] !== $this->data['pay_password_confirm']) {
                throw new AdminException('支付密码不一致');
            }
            unset($this->data['pay_password_confirm']);
            //密码加密
            if (!empty($this->data['pay_password'])) {
                $this->data['pay_salt'] = Hash::make($this->data['pay_password']);
                $salt = $this->data['pay_salt'] . config("app.salt");
                $this->data['pay_password'] = md5(sha1($this->data['pay_password'] . $salt));
            }
        } else {
            $this->data['pay_password'] = $this->data['pay_password'] ?? ($this->data['password'] ?? '');
            $this->data['pay_salt'] = $this->data['pay_salt'] ?? ($this->data['salt'] ?? '');
        }

        $admin_info = LoginUtil::getUserInfo();
        $is_open = $this->getData('is_open', 1);
        if (data_get($admin_info, 'is_open', 1) == 1 && $is_open == 0) throw new AdminException('权限不够，无法设置权限为校验无效');

        $id = $this->getData('id','');
        $password = $this->getData('password','');
        if (empty($id) && empty($password)) {
            throw new AdminException('新增用户请输入密码');

        }
        $account = data_get($this->data, 'account','');
        $phone = data_get($this->data, 'phone','');
        if (!empty($phone)){
            $phone_info =  AdminUsersModel::query()->where('phone',$phone)->first();
            if (!empty($id)) $phone_info =  AdminUsersModel::query()->where('id','!=',$id)->where(['phone'=>$phone,'guards'=>'admin'])->first();
            if (!empty($phone_info)) throw new AdminException('手机号码已被占用');
        }
        if ($account) {
            $admin_id = AdminUsers::query()->where('account', $account)->value('id');
            if ($admin_id && $id <> $admin_id) {
                throw new AdminException('该登录账号已被其他人使用');
            }
        }

        $department_ids = data_get($this->data, 'department_ids',[]);
//        if (empty($department_ids)) throw new AdminException('请选择部门');

        $role_id = $this->getData('role_id');

        if (!empty($role_id)) {
            $role_id = is_array($role_id) ? implode(',', $role_id) : $role_id;
            $this->setData("role_id", $role_id);
            $this->setData("role_list", explode(",", $role_id));
        }
    }

    public function _after_save()
    {
        $id = $this->getData('id', 0);
        $role_ids = $this->getData('role_list', []);
        if (!empty($id)) {
            LoginUtil::clearMenu($id);
        }
        if (!empty($role_ids) && !empty($id)) {
            $this->updateUserRoles($id, $role_ids);
        }

        //用户信息新增部门 支持多个部门
        if (isset($this->data['department_ids']) && is_array($this->data['department_ids'])){
            AdminUserDepartmentsModel::where('admin_user_id',$id)->delete();
            foreach ($this->data['department_ids'] as $department_id){
                AdminUserDepartmentsModel::create([
                   'department_id' => $department_id,
                   'admin_user_id' => $id
                ]);
            }
        }

        //用户信息新增直属上司 支持多个
        if (isset($this->data['parent_ids']) && is_array($this->data['parent_ids'])){
            AdminUserParentsModel::where('admin_user_id',$id)->delete();
            foreach ($this->data['parent_ids'] as $parent_id){
                AdminUserParentsModel::create([
                    'parent_id' => $parent_id,
                    'admin_user_id' => $id
                ]);
            }
        }
    }

    public function updateUserRoles($id, $role_ids)
    {
        $install_user_role_data = [];
        foreach ($role_ids as $k => $v) {
            $install_user_role_data[$k] = [
                'admin_user_id' => $id,
                'role_id' => $v,
                'is_valid' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'created_by_admin_id' => LoginUtil::getUserId(),
                'updated_by_admin_id' => LoginUtil::getUserId()
            ];
        }

        //批量 更新 用户角色表 为无效
        AdminUsersRolesModel::query()->where('admin_user_id', '=', $id)->delete();
        //批量插入角色表
        AdminUsersRolesModel::query()->insert($install_user_role_data);
    }

    /**
     * 获取当前管理员信息
     * @param array $field 获取字段
     * @return mixed
     */
    public function getManageInfo($field = ['*'])
    {
        $model = $this->model;
        $query = $model->query()->select($field);

        $result = $query->where('id', LoginUtil::getUserId())->first();
        $result = $result->toArray();
        if (!empty($result)) {
            unset($result['salt']);
            unset($result['pay_salt']);
        }

       return $result;
    }

}
